package com.rightsidetech.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.exception.BizException;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.store.*;
import com.rightsidetech.system.dtos.response.StoreSystemIntegralDetailResp;
import com.rightsidetech.system.dtos.response.store.*;
import com.rightsidetech.system.entity.store.SysStoreAccountInfo;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.entity.store.SysStoreIntegralRecord;
import com.rightsidetech.system.entity.store.SysStoreIntegralRecordDetail;
import com.rightsidetech.system.mapper.SysStoreAccountInfoMapper;
import com.rightsidetech.system.mapper.SysStoreInfoMapper;
import com.rightsidetech.system.mapper.SysStoreIntegralRecordDetailMapper;
import com.rightsidetech.system.mapper.SysStoreIntegralRecordMapper;
import com.rightsidetech.system.service.SysStoreIntegralService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("sysStoreIntegralService")
public class SysStoreIntegralServiceImpl implements SysStoreIntegralService {

    @Resource
    private SysStoreAccountInfoMapper sysStoreAccountInfoMapper;
    @Resource
    private SysStoreIntegralRecordMapper sysStoreIntegralRecordMapper;
    @Resource
    private SysStoreIntegralRecordDetailMapper sysStoreIntegralRecordDetailMapper;
    @Resource
    private SysStoreInfoMapper sysStoreInfoMapper;

    @Override
    public ResponseData<PageInfo<StoreIntegralResp>> page(StoreIntegralPageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<StoreIntegralResp> result = sysStoreAccountInfoMapper.selectIntegralList(req);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public List<StoreIntegralResp> selectIntegralList(StoreIntegralPageReq req) {
        return sysStoreAccountInfoMapper.selectIntegralList(req);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData awardIntegral(StoreAwardIntegralReq req,String operateName,Long operateId) throws Exception{
        SysStoreAccountInfo accountInfo = sysStoreAccountInfoMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(accountInfo)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"未找到需要奖励的门店账户");
        }

        SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(accountInfo.getStoreId());
        if(ObjectUtil.isEmpty(sysStoreInfo)){
            return ResponseData.fail(CodeIdEnum.NonStoreInfo);
        }
        if(!StringUtils.isEmpty(req.getAreaId()) && req.getAreaId() != 0){
            if(!sysStoreInfo.getAreaId().equals(req.getAreaId())){
                return ResponseData.fail(CodeIdEnum.NonStoreInfo);
            }
        }

        SysStoreIntegralRecord record = new SysStoreIntegralRecord();
        record.setStoreInfoId(accountInfo.getStoreId());
        record.setStoreAccountId(accountInfo.getId());
        record.setIntegral(req.getIntegral());
        record.setOperateType((byte)1);
        record.setRemark(req.getRemark());
        record.setOperate(new StringBuilder().append("奖励").append(req.getIntegral()).append("积分").toString());
        record.setOperateId(operateId);
        record.setOperateName(operateName);
        record.setCreatedAt(new Date());
        if (sysStoreIntegralRecordMapper.insertSelective(record) <= 0) {
            throw new BizException("数据库更新出现错误");
        }
        BigDecimal point = accountInfo.getPoint();
        accountInfo = new SysStoreAccountInfo();
        accountInfo.setId(req.getId());
        accountInfo.setPoint(point.add(req.getIntegral()));
        if (sysStoreAccountInfoMapper.updateByPrimaryKeySelective(accountInfo) <= 0) {
            throw new BizException("数据库更新出现错误");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<PageInfo<StoreIntegralDetailResp>> detailPage(StoreIntegralDetailReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        //判断大区帐号和查询帐号属于同一大区
        if(!StringUtils.isEmpty(req.getAreaId())){
            SysStoreAccountInfo sysStoreAccountInfo = sysStoreAccountInfoMapper.selectByPrimaryKey(req.getId());
            if(StringUtils.isEmpty(sysStoreAccountInfo)){
                return ResponseData.fail(CodeIdEnum.NonStoreInfo);
            }

            SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(sysStoreAccountInfo.getStoreId());
            if(StringUtils.isEmpty(sysStoreInfo) || !sysStoreInfo.getAreaId().equals(req.getAreaId())){
                return ResponseData.fail(CodeIdEnum.NonStoreInfo);
            }
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<StoreIntegralDetailResp> result = sysStoreIntegralRecordMapper.selectIntegralList(req);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public ResponseData<PageInfo<StoreIntegralRecordResp>> recordPage(StoreIntegralRecordReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<StoreIntegralRecordResp> result = sysStoreIntegralRecordMapper.selectPageList(req);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public List<StoreIntegralRecordResp> selectList(StoreIntegralRecordReq req){
        return sysStoreIntegralRecordMapper.selectPageList(req);
    }

    @Override
    public int insert(SysStoreIntegralRecord record) {
        return sysStoreIntegralRecordMapper.insertSelective(record);
    }

    @Override
    public ResponseData<PageInfo<StoreAppIntegralResp>> storeAppPage(PageRequest req, Long storeId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<StoreAppIntegralResp> result = sysStoreIntegralRecordMapper.selectStoreAppPage(storeId);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public void insertCommodityIntegral(StoreCommodityIntegralReq req,Byte operateType) {
        SysStoreIntegralRecord record = new SysStoreIntegralRecord();
        record.setStoreInfoId(req.getStoreId());
        record.setIntegral(req.getIntegral());
        record.setStoreAccountId(req.getAccountId());
        record.setOrderNo(req.getOrderNo());
        if(operateType == 0){
            record.setOperate("销售商品奖励" + req.getIntegral() + "积分");
        }else if(operateType == 3){
            record.setOperate("商品退货扣除" + req.getIntegral() + "积分");
        }
        record.setOperateType(operateType);
        record.setCreatedAt(new Date());
        if (sysStoreIntegralRecordMapper.insertSelective(record) <= 0) {
            return;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",req.getList());
        map.put("recordId",record.getId());
        map.put("orderNo",req.getOrderNo());
        sysStoreIntegralRecordDetailMapper.insertList(map);
    }

    @Override
    public ResponseData detailAnDetail(Long id ,Long areaId) {
        SysStoreIntegralRecord sysStoreIntegralRecord = sysStoreIntegralRecordMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sysStoreIntegralRecord)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }

        //判断大区帐号和查询帐号属于同一大区
        if(!StringUtils.isEmpty(areaId)){
            SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(sysStoreIntegralRecord.getStoreInfoId());
            if(StringUtils.isEmpty(sysStoreInfo) || !sysStoreInfo.getAreaId().equals(areaId)){
                return ResponseData.fail(CodeIdEnum.NonStoreInfo);
            }
        }

        if (sysStoreIntegralRecord.getOperateType() == 1){
            StoreSystemIntegralDetailResp detailResp = new StoreSystemIntegralDetailResp();
            detailResp.setIntegral(sysStoreIntegralRecord.getIntegral());
            detailResp.setOperateName(sysStoreIntegralRecord.getOperateName());
            detailResp.setRemark(sysStoreIntegralRecord.getRemark());
            return ResponseData.success(detailResp);
        }

        List<StoreIntegralDetailAnDetailResp> result = sysStoreIntegralRecordDetailMapper.selectListByRecordId(id);
        return ResponseData.success(result);
    }

    @Override
    public SysStoreIntegralRecord selectByOrderNo(String orderNo) {
        return sysStoreIntegralRecordMapper.selectByOrderNo(orderNo);
    }

    @Override
    public List<SysStoreIntegralRecordDetail> selectByRecordId(Long recordId) {
        return sysStoreIntegralRecordDetailMapper.selectBaseByRecordId(recordId);
    }

    @Override
    public Long findIntegralByDate(String date, Long storeId) {
        return sysStoreIntegralRecordMapper.selectIntegralStatisByDate(date,storeId);
    }

    @Override
    public Long findCurrentPointByStoreId(Long storeId) {
        SysStoreAccountInfo sysStoreAccountInfo = sysStoreAccountInfoMapper.selectByStoreId(storeId);
        return (null != sysStoreAccountInfo ? sysStoreAccountInfo.getPoint().longValue():0);
    }

    @Override
    public void integralSave(StoreCommodityIntegralReq req) {
        SysStoreIntegralRecord record = new SysStoreIntegralRecord();
        record.setStoreInfoId(req.getStoreId());
        record.setIntegral(req.getIntegral());
        record.setStoreAccountId(req.getAccountId());
        record.setOrderNo(req.getOrderNo());
        record.setOperateType((byte)4);
        record.setOperate("积分兑换扣除" + req.getIntegral().intValue() + "积分");
        record.setCreatedAt(new Date());
        if (sysStoreIntegralRecordMapper.insertSelective(record) <= 0) {
            return;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",req.getList());
        map.put("recordId",record.getId());
        map.put("orderNo",req.getOrderNo());
        sysStoreIntegralRecordDetailMapper.insertList(map);
    }
}
